package cn.kgc.springboot.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONUtil;
import cn.kgc.springboot.entity.User;
import cn.kgc.springboot.service.UserService;
import cn.kgc.springboot.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.Line;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: mosin
 * @version: v1.0  2022/11/10
 */
@RestController
@RequestMapping("user")
//@CrossOrigin  //  当前接口允许跨域请求
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    //登录
    @GetMapping("login")
    public  Object  login(String code,HttpServletRequest request){

        HashMap<String, Object> map = new HashMap<>();
        String id = request.getSession().getId();
        System.out.println("session id = " + id);
        String redisCode = redisUtil.getValue(id);
        if(redisCode==null){
            map.put("msg", "验证码已过期");
        }else {
            if(redisCode.equals(code)){
                map.put("msg", "验证码正确");
            }else {
                map.put("msg", "验证码错误");
            }
        }
        return  map;
    }


    //获取验证码
    @GetMapping("getCode")
    public  Object  getCode(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        LineCaptcha lineCaptcha = new LineCaptcha(100, 100, 4, 5);
        String code = lineCaptcha.getCode();
        String id = request.getSession().getId();
        redisUtil.setValue(id, code,30L, TimeUnit.SECONDS);
        map.put(id, code);
        map.put("msg", "验证码在30s之内有效");
        return  map;
    }


    @GetMapping("all")
    public Object getAll(){
        // 判定redis中是否有用户列表数据
        String userList = redisUtil.getValue("userList");
        if (userList!=null){
            System.out.println("数据查询结果来自redis");
            return  userList;
        }else {
            System.out.println("数据查询结果来自mysql");
            List<User> list = userService.list();
            String s = JSONUtil.toJsonStr(list);
            redisUtil.setValue("userList", s);
            return list;
        }

    }

    @GetMapping("delete")
    public Object delete(Integer id){

        userService.removeById(id);
        if (redisUtil.hasKey("userList")){
            //清空缓存
            redisUtil.deleteByKey("userList");
        }

        return "ok";
    }
}
